﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Core
{
    public class WindowFuncs
    {
        #region Invokes

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string
        lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        #endregion

        public WindowFuncs() { }

        public bool WinExistsByName(string windowName)
        {
            IntPtr hWnd = WindowSearchByName(windowName);
            if (hWnd != IntPtr.Zero)
                return true;

            return false;
        }

        public IntPtr WindowSearchByName(string windowName)
        {
            return FindWindow(null , windowName);
        }

        public void KillWindowByName(string windowName)
        {
            IntPtr hWnd = WindowSearchByName(windowName);
            if (hWnd != IntPtr.Zero)
                KillWindowByHwnd(hWnd);
        }

        public void KillWindowByHwnd(IntPtr hWnd)
        {
            uint lngPid;
            GetWindowThreadProcessId(hWnd, out lngPid);
            Process aproc = Process.GetProcessById((int)lngPid);
            try
            {
                aproc.Kill();
            }
            catch (Exception) { }
        }

        public void CloseWindowByName(string windowName)
        {
            IntPtr hWnd = WindowSearchByName(windowName);
            if (hWnd != IntPtr.Zero)
                SendCloseMessage(hWnd);
        }

        public void SendCloseMessage(IntPtr hWnd)
        {
            PostMessage(hWnd, (uint)0x010, IntPtr.Zero, IntPtr.Zero);
        }
    }
}
